﻿using Newtonsoft.Json;

namespace ShoppingCart.Models
{
    /// <summary>
    /// 购物车
    /// </summary>
    public class Cart
    {
        public List<CartItem> Items { get; set; } = new List<CartItem>();

        /// <summary>
        /// 序列化为 JSON 字符串
        /// </summary>
        /// <returns></returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this);
        }

        /// <summary>
        /// 从 JSON 字符串反序列化
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static Cart FromJson(string json)
        {
            return JsonConvert.DeserializeObject<Cart>(json);
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="item"></param>
        public void AddItem(CartItem item)
        {
            var existingItem = Items.FirstOrDefault(i => i.ProductId == item.ProductId);
            if (existingItem != null)
            {
                existingItem.Quantity += item.Quantity;
            }
            else
            {
                Items.Add(item);
            }
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="productId"></param>
        public void RemoveItem(int productId)
        {
            var item = Items.FirstOrDefault(i => i.ProductId == productId);
            if (item != null)
            {
                Items.Remove(item);
            }
        }

        /// <summary>
        /// 更新商品数量
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="quantity"></param>
        public void UpdateItemQuantity(int productId, int quantity)
        {
            var item = Items.FirstOrDefault(i => i.ProductId == productId);
            if (item != null)
            {
                item.Quantity = quantity;
            }
        }

        /// <summary>
        /// 获取购物车总价格
        /// </summary>
        /// <returns></returns>
        public decimal? GetTotalPrice()
        {
            return Items.Sum(i => i.Price * i.Quantity);
        }
    }
}
